// 点击返回至上一层
document.querySelector('.icon-fanhui').addEventListener('click',()=>{
  history.go(-1)
})

// 获取对象
const btn =document.querySelector('.search_content_right a')

// 打开search重新渲染
let arr = JSON.parse(localStorage.getItem('searchContent')) || []
searchRender()

// 判断最近搜索是否需要显示出来
if(arr.length === 0) {
  document.querySelector('.history').style.display = 'none'
}

// 点击搜索
btn.addEventListener('click', async ()=>{
  // 获取表单数据
  const search = document.querySelector('.search_content_box input').value
  if(search==='')return
  // console.log(search)
  const result = await axios({url:'/goods/list',params:{goodsName:search}})
  // console.log(result)
  // 搜索的商品存入本地
  localStorage.setItem('goodsList',search)

  // 判断搜索的内容是不是重复的
 const repeat = arr.some(item=>{
    return item === search
  })
  if(repeat) {
    arr = arr
  } else {
    arr.unshift(search)
  }

  // 最近搜索点击渲染
  localStorage.setItem('searchContent',JSON.stringify(arr))
  searchRender()
  // 搜索框清空
  document.querySelector('.search_content_box input').value=''
  // 跳转页面
  location.href='./list.html'  
})

// 点击删除
document.querySelector('.icon-ashbin').addEventListener('click',()=>{
  document.querySelector('.recent_searches').innerHTML=''
  localStorage.removeItem('searchContent')
  arr = []
  if(arr.length === 0) {
    document.querySelector('.history').style.display = 'none'
  }
})

// 点击回显
document.querySelector('.recent_searches').addEventListener('click',e =>{
  // console.log(e.target.tagName)
  if(e.target.tagName==='SPAN'){
    console.log(e.target.dataset.id)
    document.querySelector('.search_content_box input').value = arr[e.target.dataset.id]
    btn.click()
    document.querySelector('.search_content_box input').value = ''
  }
})


// 渲染最近搜索框
function searchRender() {
  document.querySelector('.recent_searches').innerHTML= arr.map((item,index)=>{
    return `<span class="search" data-id="${index}">${item}</span>  `
  }).join('')
}
